package com.leadingsoft.pwxk.service.impl;

import javax.persistence.EntityManager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.leadingsoft.pwxk.dto.AuditCertDto;
import com.leadingsoft.pwxk.model.AuditCert;
import com.leadingsoft.pwxk.model.QAuditCert;
import com.leadingsoft.pwxk.model.QSummary;
import com.leadingsoft.pwxk.repository.AuditCertRepository;
import com.leadingsoft.pwxk.service.AuditCertService;
import com.querydsl.core.Tuple;
import com.querydsl.jpa.impl.JPAQuery;

@Service
public class AuditCertServiceImpl implements AuditCertService {

	@Autowired
	private EntityManager em;

	private QAuditCert qAuditCert = QAuditCert.auditCert;

	private QSummary qSummary = QSummary.summary;

	@Autowired
	AuditCertRepository auditCertRepository;

	@Override
	public AuditCert getByDataId(String dataId) {
		return auditCertRepository.findByDataid(dataId);
	}

	@Override
	public AuditCertDto getOne(String dataId) {
		JPAQuery<Tuple> query = new JPAQuery<Tuple>(em);
		query.select(qAuditCert.dataid, qAuditCert.fzdept, qAuditCert.fztime, qAuditCert.times,
				qAuditCert.xkzfmnum, qAuditCert.xkzhfjgjb, qAuditCert.xkznum, qSummary.isversion, qSummary.creditcode,
				qSummary.itemtype);
		query.from(qAuditCert).leftJoin(qSummary).on(qAuditCert.dataid.eq(qSummary.dataid));
		
		query.where(qAuditCert.dataid.eq(dataId));
		query.orderBy(qAuditCert.fztime.desc());
		Tuple fetchOne = query.fetchFirst();
		AuditCertDto auditCertDto = new AuditCertDto();
		auditCertDto.setDataid(fetchOne.get(qAuditCert.dataid));
		auditCertDto.setCreditcode(fetchOne.get(qSummary.creditcode));
		auditCertDto.setFzdept(fetchOne.get(qAuditCert.fzdept));
		auditCertDto.setFztime(fetchOne.get(qAuditCert.fztime));
		auditCertDto.setIsversion(fetchOne.get(qSummary.isversion));
		auditCertDto.setItemtype(fetchOne.get(qSummary.itemtype));
		auditCertDto.setTimes(fetchOne.get(qAuditCert.times));
		auditCertDto.setXkzfmnum(fetchOne.get(qAuditCert.xkzfmnum));
		auditCertDto.setXkzhfjgjb(fetchOne.get(qAuditCert.xkzhfjgjb));
		auditCertDto.setXkznum(fetchOne.get(qAuditCert.xkznum));
		return auditCertDto;
	}

}
